﻿#region Using directives
using System;
using System.ComponentModel;
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;

#endregion

namespace ProcolServices {
    /// <summary>
    /// Summary description for UserInterestService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    public class UserInterestService : WebService {
        private readonly ProcolDataContext db = new ProcolDataContext();

        [WebMethod]
        //Return -2 when you find invalid input
        //Return 1 when the insertion of a UserInterest is succesfull.
        public int addUserInterest(int userId, int interestId) {
            var values = new Object[] {userId, interestId};
            foreach (var value in values) {
                String str = value.ToString();
                int tryParse;

                if (Int32.TryParse(str, out tryParse)) {
                    if (tryParse < 0)
                        return -2;
                } else if (String.IsNullOrEmpty(str))
                    return -2;
            }
            try {
                var newUserInterest = new UserInterest {UserId = userId, InterestId = interestId,};
                db.UserInterests.InsertOnSubmit(newUserInterest);
                db.SubmitChanges();

                return 1;
            } catch (InvalidOperationException) {
                return -2;
            }
        }

        [WebMethod]
        //Return -2 when you find invalid input
        //Return 1 when the insertion of a UserInterest is succesfull.
        public int addUserInterest(String username, String interest) {
            var values = new Object[] {username, interest};

            foreach (var value in values) {
                String str = value.ToString();
                int tryParse;

                if (Int32.TryParse(str, out tryParse)) {
                    if (tryParse < 0)
                        return -2;
                } else if (String.IsNullOrEmpty(str))
                    return -2;
            }

            try {
                int userId = (from u in db.Users
                              where u.Username == username
                              select u.UserId).Single();

                int interestId = (from inte in db.InterestNames
                                  where inte.Name == interest
                                  select inte.InterestId).Single();

                var newUserInterest = new UserInterest {UserId = userId, InterestId = interestId,};
                db.UserInterests.InsertOnSubmit(newUserInterest);
                db.SubmitChanges();

                return 1;
            } catch (InvalidOperationException) {
                return -2;
            }
        }
    }
}